//
//  UMManager.m
//  MSHD
//
//  Created by HCreater on 2018/1/8.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "UMManager.h"

#import "UMessage.h"
#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>
#import <UserNotifications/UserNotifications.h>
#import <UMCommon/UMCommon.h>

#import "LoadingViewController.h"

#define UM_APPKEY @"5b3f3dbca40fa337580000a6"

@interface UMManager() <UNUserNotificationCenterDelegate>

@end

@implementation UMManager

MHSingletonM(UMManager);

- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self initData];
    }
    
    return self;
}

- (void)initData
{
    _devToken = @"";
}

- (void)init:(AppDelegate*)appdelegate launchOptions:(NSDictionary*)lOptions
{
   [self configUMCommon];
    
#if TARGET_IPHONE_SIMULATOR
#else
    [self configUMessagePlatforms:lOptions];
#endif
    
    [self configUMShare];
}

- (BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭U-Push自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    
    //    self.userInfo = userInfo;
    //    //定制自定的的弹出框
    //    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    //    {
    //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
    //                                                            message:@"Test On ApplicationStateActive"
    //                                                           delegate:self
    //                                                  cancelButtonTitle:@"确定"
    //                                                  otherButtonTitles:nil];
    //
    //        [alertView show];
    //
    //    }
}

//iOS10新增：处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Push object:@{@"IsFront":@YES, @"UserInfo":userInfo[@"extra"]}];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        if ([[AppDelegate sharedDelegate].window.rootViewController isKindOfClass:[LoadingViewController class]])
        {
            [[DataManager sharedDataManager] savePushData:userInfo[@"extra"]];
        }
        else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Push object:@{@"IsFront":@NO, @"UserInfo":userInfo[@"extra"]}];
        }
    }
    else
    {
        //应用处于后台时的本地推送接受
    }
}

#pragma mark - 配置
- (void)configUMCommon
{
    [UMConfigure setLogEnabled:YES];
    [UMConfigure initWithAppkey:UM_APPKEY channel:@"App Store"];
}

- (void)configUMessagePlatforms:(NSDictionary*)lOptions
{
    //初始化方法,也可以使用(void)startWithAppkey:(NSString *)appKey launchOptions:(NSDictionary * )launchOptions httpsenable:(BOOL)value;这个方法，方便设置https请求。
    [UMessage startWithAppkey:UM_APPKEY launchOptions:lOptions];
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
}

- (void)configUMShare
{
    [self confitUShareSettings];
    
    [self configUSharePlatforms];
}

- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

- (void)configUSharePlatforms
{
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:UM_APPKEY];
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxa870b1ca63a60a54" appSecret:@"a37ad4e9e934b5c8ed63ff59861bd2a5" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105821097"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    /* 设置新浪的appKey和appSecret */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}

#pragma mark - 推送
- (void)bindAlias:(NSString*)aliasName
{
    [UMessage setAlias:aliasName type:@"STY" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
       
        if (error)
        {
            
        }
    }];
}

- (void)removeAlias:(NSString*)aliasName
{
    [UMessage removeAlias:aliasName type:@"STY" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (error)
        {
            
        }
    }];
}

#pragma mark - 分享
- (void)shareWebUrl:(NSString*)weburl
{
    BOOL isHaveQQ = [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"mqqapi://"]];
    isHaveQQ = NO;
    BOOL isHaveWechat = [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"weixin://"]];
    
    NSMutableArray* appPlatforms = [NSMutableArray array];
    if (isHaveWechat)
    {
        [appPlatforms addObject:@(UMSocialPlatformType_WechatSession)];
    }
    
    if (isHaveQQ)
    {
        [appPlatforms addObject:@(UMSocialPlatformType_QQ)];
    }
    
    [UMSocialUIManager setPreDefinePlatforms:appPlatforms];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo)
    {
        // 根据获取的platformType确定所选平台进行下一步操作
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"生态云" descr:@"" thumImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = weburl;
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:[AppDelegate sharedDelegate].window.rootViewController completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    
                    [MBProgressHUD mh_showTips:@"分享成功"];
                    
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                    
                    [MBProgressHUD mh_showTips:@"分享失败"];
                }
            }
        }];
    }];
}

@end
